import { createSlice } from "@reduxjs/toolkit"
import { userGetUserInfo, userLogin } from "../../apis/user"
import { getToken, setToken as _setToken, getUserInfo, setUserInfo as _setUserInfo, removeToken, removeUserInfo } from "../../utils"
const userStore = createSlice({
  name: 'user',
  initialState: {
    token: getToken() || '',
    userInfo: getUserInfo() || {}
  },
  reducers: {
    setToken: (state, action) => {
      state.token = action.payload
      _setToken(action.payload)
    },
    setUserInfo: (state, action) => {
      state.userInfo = action.payload
      _setUserInfo(action.payload)
    },
    clearUserInfo: (state) => {
      state.token = ''
      state.userInfo = {}
      removeToken()
      removeUserInfo()
    }
  }

})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions
const userReducer = userStore.reducer
// 获取用户token的异步方法
const fetchLogin = (data) => {
  return async (dispatch) => {
    const res = await userLogin(data)
    dispatch(setToken(res.data.data.token))
  }
}
// 获取用户信息的异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await userGetUserInfo()
    dispatch(setUserInfo(res.data.data))
  }
}
export { fetchLogin, fetchUserInfo, clearUserInfo }
export default userReducer